/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.simulation;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
/**
 *
 * @author tinnycatlen
 */
public class Spring extends JPanel implements Runnable{
    
    
    static double pos = 300;//方块位置
    static double v = 5;//方块速度
    static double m = 1;//重物质量
    static double R = 400;//弹簧静止长度
    static double k = 10;//弹簧刚度
    static double b = 0.5;//阻尼常数
    static double g = 9.8;//重力加速度
    static double a = 0;//方块加速度
    
    public static void set(double m1,double R1,double k1,double b1,double g1){
        m=m1;
        R=R1;
        k=k1;
        b=b1;
        g=g1;
    }
    
    static int n = 10;//弹簧的显示段数
    public static int getn(){
        return n;
    }
    public static void setn(int num){
        n=num;
    }
    
    public static void setpos(double p){
        pos = p;
    }
    
    @Override
    public void run(){
        while(true){
            if(MenuList.b.getState()||MenuList.g.getState()){
                if(MenuList.b.getState()){
                    a = (g-k/m*(pos-R))/3000;
                }
                else{
                    a = (-k/m*(pos-R)-b/m*v)/3000;
                }
            }
            else{
                a = (g-k/m*(pos-R)-b/m*v)/3000;
            }
            v = v+a;
            pos = pos+v;
             
            super.repaint();
            try {
            Thread.sleep(10);
            } catch (InterruptedException e) {
            e.printStackTrace();
            }
        }
    }
    @Override
    public void paint(Graphics g){
        super.paint(g);
        g.setColor(new Color(3,22,52));
        g.drawLine(200, 20, 400, 20);
        g.drawLine(300, 20, 300, 40);
        int flag = 1;
        for(int i=1;i<2*(n+1);i=i+2){
            if(i==1){
                g.drawLine(280, 40+((int)pos-40)/(2*n), 300, 40);
            }
            else if(i==2*n+1){
                g.drawLine(300+flag*20,(int)pos-((int)pos-40)/(2*n),300,(int)pos);
            }
            else{
                g.drawLine(300+flag*20, 40+((int)pos-40)*(i-2)/(2*n), 300-flag*20, 40+((int)pos-40)*i/(2*n));                
            }
            flag=-flag;
        }
        g.drawLine(300,(int)pos,300,(int)pos+20);
        g.fill3DRect(270, (int)pos+20, 60, 40,true);
    }
}
